package com.lzlearn.springboothibernate.dao.impl;

import com.lzlearn.springboothibernate.dao.OldcriteriaDao;
import com.lzlearn.springboothibernate.model.User;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository
public class OldcriteriaDaoImpl implements OldcriteriaDao {
    @Resource
    private EntityManager entityManager;
    @Override
    public List<User> criCondition(String name, Integer pageIndex, Integer pageCount) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery  = criteriaBuilder.createQuery(User.class);
       //创建查询条件
        Root<User> userRoot = criteriaQuery .from(User.class);
        Predicate name1 = criteriaBuilder.like(userRoot.get("name"), "%" + name + "%");
        //in查询
        Predicate email = criteriaBuilder.in(userRoot.get("email").in(new Object[]{"test20@baomidou.com","test19@baomidou.com"}));
        //多条件拼接
        criteriaBuilder.and(name1,email);
        //将条件对象封装进入查询对象
        Query query=entityManager.createQuery(criteriaQuery);
        query.setFirstResult((pageIndex-1)*pageCount+1);
        query.setMaxResults(pageCount);
        List resultList = query.getResultList();
        return resultList;
    }
}
